package com.example.feidaolumanager.viewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.feidaolumanager.api.RetrofitClient
import com.example.feidaolumanager.pojo.LoginVo
import com.example.feidaolumanager.pojo.RegisterDTO
import com.example.feidaolumanager.pojo.ResponseDTO
import com.example.feidaolumanager.pojo.User
import kotlinx.coroutines.launch

class LoginViewModel : ViewModel() {


    val loginSuccess = MutableLiveData<Boolean?>(null)
    val registerResponse:MutableLiveData<ResponseDTO<Boolean>?> = MutableLiveData(null)
    var user: MutableLiveData<User?> = MutableLiveData()

    fun login(loginVo: LoginVo) {

        viewModelScope.launch {
            val responseDTO = RetrofitClient.loginService.login(loginVo)

            if (responseDTO.code == 1) {
                user.value = responseDTO.data
                // 观察太慢了，直接赋值
//                RetrofitClient.token = responseDTO.data!!.token
                Log.i(this@LoginViewModel.toString(), "获取用户信息成功${user.value.toString()}")
                loginSuccess.value = true


            } else {
                loginSuccess.value = false
            }
        }
    }

    fun register(registerDTO: RegisterDTO) {
        viewModelScope.launch {
            val responseDTO = RetrofitClient.loginService.register(registerDTO)

            registerResponse.value = responseDTO
        }
    }
}